package m.system;

import m.common.action.Action;
import m.common.service.HostInfoService;
import m.system.db.TransactionManager;
import m.system.util.ClassUtil;
import m.system.util.DateUtil;
import m.system.util.JSONMessage;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

public abstract class SystemTaskRun implements Job {
	/**
	 * 定时运行方法
	 *  isMain 是否主控服务器, 如果需要更新sql,建议只在true的情况下执行
	 */
	public abstract void run(boolean isMain) throws Exception;

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		boolean isMain= HostInfoService.isMainHost();
		try {
			//HostInfo host=RuntimeData.getHostInfo();
			String method=(String) arg0.getMergedJobDataMap().get("method");
			ClassUtil.executeMethod(this, method, new Class<?>[] {boolean.class}, new Object[] {isMain});
			//run(isMain);
		} catch (Exception e) {
			Exception target=e instanceof InvocationTargetException?(Exception) ((InvocationTargetException)e).getTargetException():e;
			JSONMessage json=new JSONMessage();
			json.push("isMain",isMain).push("startDate",arg0.getTrigger().getStartTime()).push("nextDate",arg0.getTrigger().getNextFireTime());
			Action.directLog("定时任务异常", DateUtil.format(new Date()),
					arg0.getJobDetail().getJobClass().getName()+"."+arg0.getMergedJobDataMap().get("method"),
					json.toJSONString(),target);
		}finally {
			TransactionManager.closeConnection();
		}
	}
}
